import express from 'express';
import { body, validationResult, query, param } from 'express-validator';
import { Question } from '../models/index.js';
import { authenticateAdmin } from '../middleware/auth.js';
import { catchAsync, BusinessError } from '../middleware/errorHandler.js';
import { success, paginated } from '../utils/response.js';

const router = express.Router();

// 手机端用户接口已移至 /api/mobile/questions/

// 管理员接口 - 问答统计
router.get('/admin/stats',
  authenticateAdmin,
  catchAsync(async (req, res) => {
    try {
      const stats = await Question.getStatistics();

      // 计算满意度统计
      const satisfied = stats.ratings?.satisfied || 0;
      const total = stats.total || 0;

      res.json(success({
        total,
        answered: stats.answered || 0,
        satisfied
      }, '获取问答统计成功'));
    } catch (e) {
      // 兜底返回全为0
      res.json(success({
        total: 0,
        answered: 0,
        satisfied: 0
      }, '获取问答统计成功'));
    }
  })
);

// 管理员接口 - 获取问答列表
router.get('/admin/list',
  authenticateAdmin,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('expert_id').optional().isInt({ min: 1 }).withMessage('专家ID必须是正整数'),
    query('user_id').optional().isInt({ min: 1 }).withMessage('用户ID必须是正整数'),
    query('status').optional().isIn(['pending', 'answered', 'failed']).withMessage('状态参数无效'),
    query('rating').optional().isIn(['unsatisfied', 'normal', 'satisfied']).withMessage('评分参数无效')
  ],
  catchAsync(async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new BusinessError('参数验证失败', errors.array());
    }

    const { page = 1, limit = 20, expert_id, user_id, status, rating } = req.query;
    const where = {};
    
    if (expert_id) where.expert_id = parseInt(expert_id);
    if (user_id) where.user_id = parseInt(user_id);
    if (status) where.status = status;
    if (rating) where.rating = rating;
    
    const result = await Question.findAndCountAll({
      where,
      include: [
        { association: 'user', attributes: ['id', 'phone'] },
        { 
          association: 'expert', 
          attributes: ['id', 'nickname'],
          include: [{ 
            association: 'domain', 
            attributes: ['id', 'name'] 
          }]
        },
        { association: 'quota', attributes: ['id', 'quota_type'] }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });
    
    res.json(paginated(result.rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: result.count,
      pages: Math.ceil(result.count / parseInt(limit))
    }, '获取问答记录成功'));
  })
);

export default router;
